//
//  MailListView.m
//  OASystem
//
//  Created by macos on 14-4-17.
//  Copyright (c) 2014年 macos. All rights reserved.
//

#import "MailListView.h"

@interface MailListView ()

@end

@implementation MailListView
@synthesize mailListMutArr;
@synthesize mailTypeStr;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        if(!mailListMutArr)
            mailListMutArr = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)backUpdata
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
    back = 1;
    [[SendHttpOperation shareSendHttpOperation] GetMailList:@"GetMailList.ashx"
                                                        Cur:@"0"
                                                       Rows:@"10"
                                                BoxTypeGuid:mailTypeStr
                                                   haveread:@"2"
                                              ownerUserGuid:USER_OWNER_GUDID];
    [SendHttpOperation shareSendHttpOperation].getOfficalMailDelegate = self;
}

//返回上一级
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initNavi
{
    //初始化UINavigation
    self.navigationItem.titleView = [[UIView alloc] initWithFrame:CGRectMake(110, 0, 100, 44)];
    UILabel *titleLabel           = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    NSString *titleStr            = [mailTypeStr isEqualToString:@"100000"]?@"收件箱":([mailTypeStr isEqualToString:@"100001"]?@"发件箱":@"草稿箱");
    titleLabel.text               = titleStr;
    titleLabel.font               = HEIGHT_FONT(18.0f);
    titleLabel.textAlignment      = NSTextAlignmentCenter;
    titleLabel.backgroundColor    = [UIColor clearColor];
    titleLabel.textColor          = [UIColor whiteColor];
    [self.navigationItem.titleView addSubview:titleLabel];
    
    //添加导航又边用户信息
    //初始化UINavigation左按钮
    UIButton *helloButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 80, 24)];
    [helloButton setTitle:[NSString stringWithFormat:@"你好，%@",USER_NICK_NAME] forState:UIControlStateNormal];
    helloButton.titleLabel.font = HEIGHT_FONT(13.0f);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:helloButton];
    
    //初始化UINavigation左按钮
    UIButton *naviButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 45, 24)];
    [naviButton setTitle:@"返回" forState:UIControlStateNormal];
    naviButton.titleLabel.font = HEIGHT_FONT(13.0f);
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_n.png"] forState:UIControlStateNormal];
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_p.png"] forState:UIControlStateHighlighted];
    [naviButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:naviButton];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavi];
    [self pullRefresh];
}


#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [mailListMutArr count]>=10?[mailListMutArr count]+1:[mailListMutArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MailTableCell* cell = (MailTableCell*)[tableView dequeueReusableCellWithIdentifier:@"MailTableCell"];
    if (cell == nil)
    {
        NSArray* arry = [[NSBundle mainBundle] loadNibNamed:@"MailTableCell" owner:nil options:nil];
        cell = [arry objectAtIndex:0];
    }
    
    //自定义分割线
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 69, 320, 1)];
    line.backgroundColor = NOTICEBOARD_LINE_COLOR;
    [cell.contentView addSubview:line];
    
    if(mailListMutArr.count < 10 || (mailListMutArr.count>=10 && indexPath.row<mailListMutArr.count))
    {
        NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
        for (UILabel *subview in subviews)
        {
            if(subview.tag == 100)
                [subview removeFromSuperview];
        }
        
        cell.titleLabel.hidden = NO;
        cell.sendNameLabel.hidden = NO;
        cell.contentLabel.hidden = NO;
        cell.img1.hidden = NO;
        
        //添加数据
        NSString *sendNameStr = [NSString stringWithFormat:@"%@",[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:3]];//@"标题";
        NSString *hasReadStr = [NSString stringWithFormat:@"%@",[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:20]];//@"是否已读";
        NSString *titleStr = [NSString stringWithFormat:@"%@",[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:10]];//@"标题";
        NSString *contentStr = [NSString stringWithFormat:@"%@",[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:11]];//@"内容";
        NSString *hasAttack = [NSString stringWithFormat:@"%@",[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:17]];//@"是否有附件";
        
        cell.sendNameLabel.text = sendNameStr;
        if([mailTypeStr isEqualToString:@"100000"])
        {
            cell.hasReadImageView.hidden = [hasReadStr isEqualToString:@"1"]?YES:NO;
        }
        else
        {
            cell.hasReadImageView.hidden = YES;
        }
        cell.titleLabel.text = titleStr;
        
        if([temphasReadArr containsObject:[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:1]])
            cell.hasReadImageView.hidden = YES;
        
        
        if(contentStr.length != 0)
        {
            cell.contentLabel.text = [self convertHtmlStr:contentStr];
        }
//        NSRange range = [contentStr rangeOfString:@"<p>"];
//        int location = range.location;
//        NSLog(@"contentStr-->%@",contentStr);
//        NSLog(@"location-->%d",location);
//        if(location != 2147483647)
//            cell.contentLabel.text = @"";
//        else
//            cell.contentLabel.text = contentStr;
        
        cell.weekLabel.hidden = YES;
    //    cell.weekLabel.text = @"星期日";
        cell.fujianImageView.hidden = [hasAttack isEqualToString:@"1"]?NO:YES;
    }
    else
    {
        cell.titleLabel.hidden = YES;
        cell.sendNameLabel.hidden = YES;
        cell.contentLabel.hidden = YES;
        cell.fujianImageView.hidden = YES;
        cell.img1.hidden = YES;
        cell.hasReadImageView.hidden = YES;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 25, 200, 20)];
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 100;
        label.text = @"点击加载更多";
        label.font = HEIGHT_FONT(14.0f);
        [cell.contentView addSubview:label];
    }

    cell.contentView.backgroundColor = NOTICEBOARD_BACKCOLOR;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//清楚文字格式
- (NSString *)convertHtmlStr:(NSString *)paramSTr
{
    NSString *resultStr = [paramSTr stringByReplacingOccurrencesOfString :@"{^^^}" withString:@"\n"];
    resultStr = [resultStr stringByReplacingOccurrencesOfString :@"{###}" withString:@"\r"];
    
    NSRange range = [resultStr rangeOfString:@"<p>"];
    if(range.location < 100000)
    {
        resultStr = @"";
    }
    
    return resultStr;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(mailListMutArr.count < 10 || (mailListMutArr.count>=10 && indexPath.row<mailListMutArr.count))
    {
        if([mailTypeStr isEqualToString:@"100002"])
        {
            WriteEmailView *instance = [[WriteEmailView alloc] init];
            instance.draftDic = [NSArray arrayWithArray:[mailListMutArr objectAtIndex:indexPath.row]];
            instance.boolDraft = 1;
            instance.delegate = self;
            [self.navigationController pushViewController:instance animated:YES];
        }
        else
        {
            if(!temphasReadArr)
                temphasReadArr = [[NSMutableArray alloc] init];
            [temphasReadArr addObject:[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:1]];
            
            DisplayMailView *instance = [[DisplayMailView alloc] init];
            instance.passDisplayMainArr = [NSArray arrayWithArray:[mailListMutArr objectAtIndex:indexPath.row]];
            [self.navigationController pushViewController:instance animated:YES];
            
            NSLog(@"uuuii----->%@",[mailListMutArr objectAtIndex:indexPath.row]);
            if([mailTypeStr isEqualToString:@"100000"])
            {
                NSString *hasReadStr = [NSString stringWithFormat:@"%@",[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:17]];
                if([hasReadStr isEqualToString:@"0"])
                    [[SendHttpOperation shareSendHttpOperation] SetMailRead:@"SetMailRead"
                                                                   mailGuid:[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:1]];
            }
        }
        [mailListTable reloadData];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
        back = 0;
        pageIndex++;
        NSString *index = [NSString stringWithFormat:@"%d",pageIndex];
        [[SendHttpOperation shareSendHttpOperation] GetMailList:@"GetMailList.ashx"
                                                            Cur:index
                                                           Rows:@"10"
                                                    BoxTypeGuid:mailTypeStr
                                                       haveread:@"2"
                                                  ownerUserGuid:USER_OWNER_GUDID];
        [SendHttpOperation shareSendHttpOperation].getOfficalMailDelegate = self;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
        NSLog(@"yyyuu-->%@",[mailListMutArr objectAtIndex:indexPath.row]);
        [[SendHttpOperation shareSendHttpOperation] deleteMailInFlag:@"GetMailList.ashx"
                                                            mailGuid:[[mailListMutArr objectAtIndex:indexPath.row] objectAtIndex:1]];
        [SendHttpOperation shareSendHttpOperation].deleteMailInFlagDelegate = self;
    }
}

- (void)passDeleteMailInFlag:(NSDictionary *)addDraftMailDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
//    [mailListTable reloadData];
    [self backUpdata];
}

#pragma mark 重新加载下拉框
- (void)pullRefresh
{
    if(_refreshHeaderView)
    {
        [_refreshHeaderView removeFromSuperview];
    }
    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, -80, 320, 80)];
    _refreshHeaderView.delegate = self;
    [mailListTable addSubview:_refreshHeaderView];
    [_refreshHeaderView refreshLastUpdatedDate];
}

#pragma mark EGORefreshTableHeaderDelegate(上下下拉操作)
- (void)reloadTableViewDataSource
{
	product_reloading = YES;
	NSLog(@"开始获取更多数据...");
	//打开线程，加载更多数据
    back = 2;
    [[SendHttpOperation shareSendHttpOperation] GetMailList:@"GetMailList.ashx"
                                                        Cur:@"0"
                                                       Rows:@"10"
                                                BoxTypeGuid:mailTypeStr
                                                   haveread:@"2"
                                              ownerUserGuid:USER_OWNER_GUDID];
    [SendHttpOperation shareSendHttpOperation].getOfficalMailDelegate = self;
}

- (void)passOfficalMail:(NSDictionary *)officalMailDic
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
    if(back == 0)
    {
        NSLog(@"officalMailDic---%@",officalMailDic);
        if([[officalMailDic allKeys] containsObject:@"result"])
        {
            [mailListMutArr addObjectsFromArray:[[[officalMailDic objectForKey:@"result"] objectForKey:@"list"] objectForKey:@"data"]];
            [mailListTable reloadData];
            NSLog(@"---P%@",officalMailDic);
        }
//        else
//        {
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"刷新成功！"}];
//        }
//        [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
    }
    else if(back == 1)
    {
        if(!mailListMutArr)
            mailListMutArr = [[NSMutableArray alloc] init];
        mailListMutArr = [NSMutableArray arrayWithArray:[[[officalMailDic objectForKey:@"result"] objectForKey:@"list"] objectForKey:@"data"]];
        [mailListTable reloadData];
    }
    else
    {
        if([[officalMailDic allKeys] containsObject:@"result"])
        {
            if(!mailListMutArr)
                mailListMutArr = [[NSMutableArray alloc] init];
            mailListMutArr = [NSMutableArray arrayWithArray:[[[officalMailDic objectForKey:@"result"] objectForKey:@"list"] objectForKey:@"data"]];
            [mailListTable reloadData];
            NSLog(@"---P%@",officalMailDic);
        }
        else
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"刷新成功！"}];
        }
        [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
    }
}

- (void)doneLoadingTableViewData
{
    NSLog(@"加载更多结束");
    [self pullRefresh];
	product_reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mailListTable];
}

#pragma mark UIScrollViewDelegate(上拉下拉判断)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:mailListTable];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:mailListTable];
}


#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
	return product_reloading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	return [NSDate date];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
